package net.wwang.blog.commons.global;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * 输入校验处理
 *
 * @author WangWei
 * @date 2020/8/12
 */
@ControllerAdvice
public class CodeWwangExceptionHandler {
	/**
	 * 处理 Validator 框架实体类验证的错误返回
	 *
	 * @return
	 */
	@ResponseBody
	@ExceptionHandler(value = Exception.class)
	public ResponseResult BindingResult(Exception e) {
		//每次捕获第一个校验异常
		if (e instanceof MethodArgumentNotValidException) {
			MethodArgumentNotValidException methodE = (MethodArgumentNotValidException) e;
			FieldError error = (FieldError) methodE.getBindingResult().getAllErrors().get(0);
			return ResponseResult.FAILED(error.getDefaultMessage());
		}

		// 未以管理员账户登录
		if (e instanceof AccessDeniedException){
			return ResponseResult.FAILED(GlobalTipMsg.INSUFFICIENT_PERMISSIONS);
		}
		return ResponseResult.FAILED(GlobalTipMsg.OPERATION_FAILED).setData(e.toString());
	}

	private ResponseResult getErrors(BindingResult result) {
		List<String> list = new ArrayList<>();
		for (FieldError error : result.getFieldErrors()) {
			list.add(error.getDefaultMessage());
		}
		if (list != null && list.size() > 0) {
			return ResponseResult.FAILED(list.toString());
		}
		return null;
	}

}
